package cn.j229.bug.zhongxuan.hualian.controller;

import cn.j229.bug.zhongxuan.hualian.exception.BusinessException;
import cn.j229.bug.zhongxuan.hualian.pojo.User;
import cn.j229.bug.zhongxuan.hualian.service.UserService;
import cn.j229.bug.zhongxuan.hualian.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author smile_ZhongXuan
 * @Date 2020/10/21 11:18
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    RedisTemplate<String,Object> redisTemplate = null;
    @Resource
    UserService userService = null;
    JsonResult jsonResult = new JsonResult();

    @PostMapping("/register")
    public Map register(@RequestBody User user,@RequestParam(value = "captcha") String captcha){
        // 判断验证码是否合法
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        Object code = operations.get(user.getPhone());
        if(code.equals(captcha)){
            // 合法，将个人信息、注册时间 添加到数据库
            int insertUserSelective = userService.insertUserSelective(user);
            jsonResult.setCode("200");
            jsonResult.setMsg("新增会员账号成功！");
        }else if(code.equals("")){
            // 不合法，则返回注册失败：验证码已失效
            jsonResult.setCode("0");
            throw new BusinessException("验证码已失效，请重新获取。");
        }else{
            // 不合法，则返回注册失败：验证码不正确
            jsonResult.setCode("0");
            throw new BusinessException("验证码输入错误，请重新输入。");
        }
        return jsonResult.getValues();
    }

    @PostMapping("/login")
    public Map loginUser(@RequestParam("phone") String phone){
        User userByPhone = userService.findUserByPhone(phone);
        if(userByPhone == null || userByPhone.equals("")){
            jsonResult.setCode("0");
            jsonResult.setMsg("用户不存在，请注册后再进行登录。");
            throw new BusinessException("用户不存在。");
        }else{
            jsonResult.setCode("200");
            jsonResult.setMsg("登录成功");
        }
        return jsonResult.getValues();
    }
}
